<template>
  <div class="app-container">
    <div style="margin-bottom: 20px;" class="clearfix">
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-plus"
        style="float:right"
        @click="handleAdd"
      >新增</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :element-loading-text="g.loadingStr"
      :header-cell-style="{background:g.mainColor}"
    >
      <el-table-column label="序号" align="center" width="100" fixed>
        <template slot-scope="{$index}">
          <span>{{ $index + 1 + ( listQuery.currentPage - 1 ) * listQuery.pageSize }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.departName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center">
        <template slot-scope="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">
          <span>{{ row.status === 1 ? '启用' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="160px">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDel(row,$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.currentPage"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="dialogType"
      :visible.sync="dialogVisible"
      width="27%"
      @close="$refs['form'].clearValidate()"
      @opened="$refs['form'].clearValidate()"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="部门名称" prop="departName">
          <el-input
            v-model="form.departName"
            placeholder="请输入名称"
            clearable
            @change="validRepeatName"
            @input="changeInputValue"
          />
          <i v-if="isRegister == 0 && isRegister !== null " class="el-icon-check">通过</i>
          <i v-if="isRegister == 1 && isRegister !== null" class="el-icon-close">部门已存在</i>
        </el-form-item>
        <el-form-item label="部门备注">
          <el-input v-model="form.remark" type="textarea" autosize placeholder="请输入备注" clearable />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="form.status" />
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import {
  organizeDepartmentList,
  organizeDepartmentUpdate,
  organizeDepartmentAdd,
  organizeDepartmentDel,
  validateDepartmentName
} from '@/api/system'

export default {
  name: 'DepartmentList',
  directives: { waves },
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      isRegister: null,
      validValue: null,
      orgId: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 10,
        orgId: 0
      },

      rules: {
        departName: [
          {
            required: true,
            trigger: 'blur',
            validator: this.g.checkInputIsEmpty
          }
        ]
      },
      form: {
        id: '',
        departName: '',
        remark: '',
        status: false
      },
      dialogVisible: false,
      dialogType: ''
    }
  },
  created() {},
  mounted() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      organizeDepartmentList(this.listQuery).then((response) => {
        console.log(response.data)
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleUpdate(row) {
      console.log(row)
      this.dialogType = '部门编辑'
      this.isRegister = null
      this.dialogVisible = true
      this.form.id = row['id']
      this.form.departName = row['departName']
      this.form.remark = row['remark']
      this.form.status = row['status'] === 1
    },
    handleAdd() {
      this.dialogType = '部门新增'
      this.isRegister = null
      this.dialogVisible = true
      this.form.id = ''
      this.form.departName = ''
      this.form.remark = ''
      this.form.status = false
    },
    validRepeatName() {
      if (this.form.departName === '') return
      validateDepartmentName({ orgId: this.orgId, departName: this.form.departName }).then(res => {
        console.log(res.data.exist)
        this.isRegister = res.data.exist === 1 ? 1 : 0
      })
    },
    changeInputValue() {
      if (this.form.departName === '') {
        this.isRegister = null
      }
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.status = this.form.status ? '1' : '0'
          console.log(this.form.status)
          if (this.dialogType === '部门编辑') {
            if (this.isRegister === 1) {
              this.form.status = this.form.status === '1'
              return
            }
            organizeDepartmentUpdate(this.form).then((response) => {
              this.$message({ message: '提交成功', type: 'success' })
              this.dialogVisible = false
              this.getList()
            })
          } else {
            if (this.isRegister !== 0) {
              this.form.status = this.form.status === '1'
              return
            }
            organizeDepartmentAdd({
              departName: this.form.departName,
              remark: this.form.remark,
              orgId: 0,
              status: this.form.status
            }).then((response) => {
              this.$message({ message: '提交成功', type: 'success' })
              this.dialogVisible = false
              this.getList()
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleDel(row, index) {
      console.log(row)
      this.$confirm('是否确认删除该部门？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(JSON.stringify(this.multipleSelection))
        organizeDepartmentDel({
          id: row['id']
        }).then((response) => {
          this.$message({ message: '操作成功', type: 'success' })
          this.list.splice(index, 1)
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .el-input,.el-textarea{
  width: 66%;
}

// /deep/ .el-textarea{
//   width: 66%;
// }
.el-icon-check{
  margin-left: 10px;
  color: green;
}
.el-icon-close{
  margin-left: 10px;
  color: red;
}
</style>
